<script setup>
import api from './api'
import { ElMessage, ElMessageBox } from 'element-plus'

const props = defineProps({
  modelValue: { type: Object, default: () => ({}) },
  field: { type: String, default: '' },
  level: { type: [Number, String], default: 3 },
  wrap: Boolean,
  disabled: Boolean,
})

const emit = defineEmits(['update:modelValue', 'change'])

const keys = reactive({
  id: props.field ? props.field + '_area_id' : 'area_id',
  name: props.field ? props.field + '_area_name' : 'area_name',
  address: props.field ? props.field + '_address_detail' : 'address_detail',
})
const form = computed({
  get() {
    return props.modelValue
  },
  set(val) {
    emit('update:modelValue', val)
  }
})
const loadings = reactive({})

const cascaderProps = {
  lazy: true,
  lazyLoad(node, resolve) {
    const { root, value } = node
    api.query({ parent_id: root ? 0 : value }).then(res => {
      const nodes = res.data.map(item => ({
        value: item.area_id,
        label: item.area_name,
        leaf: item.level > +props.level - 1
      }))
      resolve(nodes)
    })
  },
}

const cascaderRef = ref()
const handleChange = val => {
  if (!form.value[keys.id]) {
    form.value[keys.name] = []
    return
  }
  const node = cascaderRef?.value.getCheckedNodes()[0]
  form.value[keys.name] = node.pathLabels
  emitChange()
}

const emitChange = () => {
  emit('change', form.value[keys.name].join('') + form.value[keys.address])
}

// 智能识别
const toSmart = async val => {
  let areas = val
  let area_id = 0
  const ids = []
  const names = []
  while (ids.length < +props.level) {
    const res = await api.query({ parent_id: area_id })
    const item = res.data.find(d => areas.startsWith(d.area_name))
    if (!item) {
      ElMessage.error('省/市/区填写不正确')
      return
    }
    area_id = item.area_id
    areas = areas.replace(item.area_name, '')
    ids.push(area_id)
    names.push(item.area_name)
  }
  form.value[keys.id] = ids
  form.value[keys.name] = names
  form.value[keys.address] = areas
  emitChange()
  ElMessage.success('填写成功')
}

const smart = () => {
  ElMessageBox.prompt('此处粘贴地址信息，可自动识别省/市/区+详细地址，如广东省深圳市XX区XX街道XX号', '智能填写', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern:
      /^[\u4E00-\u9FA5A-Za-z0-9_]+$/,
    inputErrorMessage: '填写有误',
  })
    .then(async({ value }) => {
      loadings.smart = true
      await toSmart(value)
      loadings.smart = false
    })
}
</script>

<template>
  <template v-if="wrap">
    <div class="flex flex-col" v-bind="$attrs">
      <v-group>
        <el-cascader ref="cascaderRef" v-model="form[keys.id]" :props="cascaderProps" class="w-full"
          @change="handleChange" />
        <el-button v-if="!disabled" type="primary" class="px-2" :loading="loadings.smart" @click="smart">智能填写</el-button>
      </v-group>
      <el-input v-model="form[keys.address]" placeholder="详细地址" clearable class="mt-1" @change="handleChange"></el-input>
    </div>
  </template>
  <v-group v-else class="w-full" v-bind="$attrs">
    <el-cascader ref="cascaderRef" v-model="form[keys.id]" :props="cascaderProps" class="w-80" @change="handleChange" />
    <el-input v-model="form[keys.address]" placeholder="详细地址" clearable @change="handleChange"></el-input>
    <el-button v-if="!disabled" type="primary" class="px-2" :loading="loadings.smart" @click="smart">智能填写</el-button>
  </v-group>
</template>